package com.kele.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.kele.common.model.response.Result;
import com.kele.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class JwtTokenFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate redisTemplate;
    private String[] skipAuthUrls =
            {"login","image/code","reg","sendSms","getSmsCodeTTL"};
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取URL
        String url = request.getURI().getPath();

        for(String skipAuthUrl:skipAuthUrls){
            if(url.contains(skipAuthUrl)){
               return chain.filter(exchange);//放行
            }
        }

        //从Authorization 头信息里面获取 Bearer token
        HttpHeaders headers = request.getHeaders();
        System.out.println(headers);

        String authorizationHeader = request.getHeaders().getFirst(JwtUtils.TOKEN_HEADER);

        if(StringUtils.isEmpty(authorizationHeader)){
            return authFail(response,"请登录");
        }
        if(!authorizationHeader.startsWith(JwtUtils.TOKEN_PREFIX)){
            return authFail(response,"请登录");
        }
        //去掉Bearer ,或者使用authorizationHeader.substring(7);
        String token = authorizationHeader.replace(JwtUtils.TOKEN_PREFIX,"");
        //
        if(StringUtils.isEmpty(token)){
            return authFail(response,"请登录");
        }else{
            //是否存在
            /*
            Long expire = redisTemplate.getExpire("token_" + token);
            System.out.println("expire = " + expire);
            String s = (String)redisTemplate.opsForValue().get("token_" + token);
            */
            Boolean flag = redisTemplate.hasKey("token_" + token);
            if(flag){
                //更新时间30
                redisTemplate.opsForValue().set("token_" + token,"1",30, TimeUnit.HOURS);
            }else{
                return authFail(response,"token超时，请重新登录");
            }

            try {
                Jws<Claims> claimsJws = JwtUtils.parseJwt(token);

                System.out.println("userId=" + claimsJws.getBody().getId());
                System.out.println("username(phone,email)=" + claimsJws.getBody().getSubject());

                //在HTTP请求中传递heder
                request.mutate().header("userid_1905A",claimsJws.getBody().getId());

                return chain.filter(exchange);//放行
            } catch (ExpiredJwtException e) {
                if (e.getMessage().contains("Allowed clock skew")) {
                    return authFail(response, "认证过期");
                } else {
                    return authFail(response, "认证失败");
                }
            }catch (Exception e) {
                return authFail(response, "认证失败");
            }
        }
    }

    /**
     * 认证错误输出
     * @param response 响应对象
     * @param msg 错误信息
     * @return
     */
    private Mono<Void> authFail(ServerHttpResponse response, String msg) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
        response.getHeaders().add("Content-Type",
                "application/json;charset=UTF-8");

        Result result = new Result(false,"401", msg);

        String response_string = JSON.toJSONString(result);
        System.out.println(response_string);

        DataBuffer buffer = response.bufferFactory()
                .wrap(response_string.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));
    }
    /**
     * 数值越小越靠前
     * @return
     */
    @Override
    public int getOrder() {
        return -10;
    }
}
